import { createMenu, updateMenu, getMenuList, deleteMenu } from '@/api/system';

// 设置菜单数据
export const setupMenuData = async () => {
  try {
    // 先检查现有菜单
    const existingMenus = await getMenuList();

    // 查找根目录ID
    const systemManagement = existingMenus.find(m => m.name === '系统管理' && m.type === 'M');
    const dataManagement = existingMenus.find(m => m.name === '数据管理' && m.type === 'M');

    // 如果不存在根目录，先创建
    let systemId = systemManagement?.id;
    let dataId = dataManagement?.id;

    if (!systemId) {
      const newSystem = await createMenu({
        pid: 0,
        name: '系统管理',
        icon: 'setting',
        path: '/system',
        redirect: '/system/users',
        type: 'M',
        visible: true,
        status: true,
        sort: 1,
        remark: '系统管理模块'
      });
      systemId = newSystem;
    } else {
      // 如果已存在，更新 redirect 字段
      await updateMenu(systemId, {
        redirect: '/system/users'
      });
    }

    if (!dataId) {
      const newData = await createMenu({
        pid: 0,
        name: '数据管理',
        icon: 'database',
        path: '/data',
        type: 'M',
        visible: true,
        status: true,
        sort: 2,
        remark: '数据管理模块'
      });
      dataId = newData;
          }

    // 定义菜单数据（使用实际的ID）
    const menuData = [
      {
        pid: systemId,
        name: '用户管理',
        icon: 'user',
        path: '/system/users',
        component: 'system/Users',
        type: 'C' as const,
        visible: true,
        status: true,
        sort: 1,
        permission: 'system:user:list',
        remark: '用户管理页面'
      },
      {
        pid: systemId,
        name: '角色管理',
        icon: 'team',
        path: '/system/roles',
        component: 'system/Roles',
        type: 'C' as const,
        visible: true,
        status: true,
        sort: 2,
        permission: 'system:role:list',
        remark: '角色管理页面'
      },
      {
        pid: systemId,
        name: '菜单管理',
        icon: 'menu',
        path: '/system/menus',
        component: 'system/Menus',
        type: 'C' as const,
        visible: true,
        status: true,
        sort: 3,
        permission: 'system:menu:list',
        remark: '菜单管理页面'
      },
      {
        pid: systemId,
        name: '日志管理',
        icon: 'file-text',
        path: '/system/logs',
        component: 'system/Logs',
        type: 'C' as const,
        visible: true,
        status: true,
        sort: 4,
        permission: 'system:log:list',
        remark: '日志管理页面'
      },
      {
        pid: dataId,
        name: '数据字典',
        icon: 'book',
        path: '/data/dict',
        component: 'data/Dict',
        type: 'C' as const,
        visible: true,
        status: true,
        sort: 1,
        permission: 'data:dict:list',
        remark: '数据字典页面'
      }
    ];

    // 定义权限数据（按钮权限）
    const permissionData = [
      // 用户管理权限
      {
        pid: systemId,
        name: '用户新增',
        type: 'F' as const,
        permission: 'system:user:create',
        sort: 1,
        remark: '用户新增权限'
      },
      {
        pid: systemId,
        name: '用户修改',
        type: 'F' as const,
        permission: 'system:user:update',
        sort: 2,
        remark: '用户修改权限'
      },
      {
        pid: systemId,
        name: '用户删除',
        type: 'F' as const,
        permission: 'system:user:delete',
        sort: 3,
        remark: '用户删除权限'
      },
      {
        pid: systemId,
        name: '用户查询',
        type: 'F' as const,
        permission: 'system:user:query',
        sort: 4,
        remark: '用户查询权限'
      },
      {
        pid: systemId,
        name: '用户导出',
        type: 'F' as const,
        permission: 'system:user:export',
        sort: 5,
        remark: '用户导出权限'
      },
      // 角色管理权限
      {
        pid: systemId,
        name: '角色新增',
        type: 'F' as const,
        permission: 'system:role:create',
        sort: 6,
        remark: '角色新增权限'
      },
      {
        pid: systemId,
        name: '角色修改',
        type: 'F' as const,
        permission: 'system:role:update',
        sort: 7,
        remark: '角色修改权限'
      },
      {
        pid: systemId,
        name: '角色删除',
        type: 'F' as const,
        permission: 'system:role:delete',
        sort: 8,
        remark: '角色删除权限'
      },
      {
        pid: systemId,
        name: '角色查询',
        type: 'F' as const,
        permission: 'system:role:query',
        sort: 9,
        remark: '角色查询权限'
      },
      // 菜单管理权限
      {
        pid: systemId,
        name: '菜单新增',
        type: 'F' as const,
        permission: 'system:menu:create',
        sort: 10,
        remark: '菜单新增权限'
      },
      {
        pid: systemId,
        name: '菜单修改',
        type: 'F' as const,
        permission: 'system:menu:update',
        sort: 11,
        remark: '菜单修改权限'
      },
      {
        pid: systemId,
        name: '菜单删除',
        type: 'F' as const,
        permission: 'system:menu:delete',
        sort: 12,
        remark: '菜单删除权限'
      },
      {
        pid: systemId,
        name: '菜单查询',
        type: 'F' as const,
        permission: 'system:menu:query',
        sort: 13,
        remark: '菜单查询权限'
      },
      // 日志管理权限
      {
        pid: systemId,
        name: '日志查询',
        type: 'F' as const,
        permission: 'system:log:query',
        sort: 14,
        remark: '日志查询权限'
      },
      {
        pid: systemId,
        name: '日志删除',
        type: 'F' as const,
        permission: 'system:log:delete',
        sort: 15,
        remark: '日志删除权限'
      },
      // 数据字典权限
      {
        pid: dataId,
        name: '字典新增',
        type: 'F' as const,
        permission: 'data:dict:create',
        sort: 16,
        remark: '字典新增权限'
      },
      {
        pid: dataId,
        name: '字典修改',
        type: 'F' as const,
        permission: 'data:dict:update',
        sort: 17,
        remark: '字典修改权限'
      },
      {
        pid: dataId,
        name: '字典删除',
        type: 'F' as const,
        permission: 'data:dict:delete',
        sort: 18,
        remark: '字典删除权限'
      },
      {
        pid: dataId,
        name: '字典查询',
        type: 'F' as const,
        permission: 'data:dict:query',
        sort: 19,
        remark: '字典查询权限'
      }
    ];

    // 创建或更新菜单
    for (const menu of menuData) {
      try {
        // 检查是否已存在相同路径的菜单
        const existingMenu = existingMenus.find(m => m.path === menu.path);

        if (existingMenu) {
          // 更新现有菜单
          await updateMenu({
            ...menu,
            id: existingMenu.id
          });
          // 更新菜单
        } else {
          // 创建新菜单
          await createMenu(menu);
          // 创建菜单
        }
      } catch {
        // 静默处理菜单处理失败
      }
    }

    // 创建或更新权限
    for (const permission of permissionData) {
      try {
        // 检查是否已存在相同权限标识的权限
        const existingPermission = existingMenus.find(m => m.permission === permission.permission);

        if (existingPermission) {
          // 更新现有权限
          await updateMenu({
            ...permission,
            id: existingPermission.id
          });
          // 更新权限
        } else {
          // 创建新权限
          await createMenu(permission);
          // 创建权限
        }
      } catch {
        // 静默处理权限处理失败
      }
    }

    // 清理重复的旧数据
    const oldPaths = ['/user', '/role', '/menu'];
    for (const path of oldPaths) {
      const oldMenu = existingMenus.find(m => m.path === path);
      if (oldMenu) {
        try {
          await deleteMenu(oldMenu.id);
          // 删除旧菜单
        } catch {
          // 静默处理删除旧菜单失败
        }
      }
    }

    // 菜单数据设置完成
  } catch {
    // 静默处理设置菜单数据失败
  }
};

export default setupMenuData;